#include"include.h"

config_t *configInit(char *fileName)
{
   config_t *config = malloc(sizeof(config_t));
   config->fileName = fileName;
   config->conf = newDict((int (*)(const void*,const void*))strcmp);
   configReloadConfig(config);
   return config;
}

void configReloadConfig(config_t *c)
{
   dictClearKeysVals(c->conf);
   FILE *f = fopen(c->fileName, "r");
   if(f == NULL)
   {
      loggerLog(LOG_ERR, "Could not open config file %s.\n", c->fileName);
      return;
   }
   loggerLog(LOG_INFO, "Loading config file %s.\n", c->fileName);
   int i,j,len;
   do
   {
      i=j=0;
      char *line = NULL;
      len = 500;
      len = getline(&line, (size_t *)&len, f);
      if(line == NULL)
	 continue;
      loggerLog(LOG_DEBUG, "Read config line %s.", line);
      if((len < 3 || line[i] == '#'))
      {
         free(line);
         continue; //Comment
      }
      for(i=0;i<len && line[i] != '=';i++);
      if(i == len)
      {
         loggerLog(LOG_WARN, "Invalid config line. Line %s\t'=' is not present.\n", line);
         free(line);
         continue; //No value. Looks like asdf or asdf=
      }
      //i is now the index of our =. We can extract left and right
      //a=b. len=3. key=a\0 val=b\0 i=1
      char *key = malloc(i + 1);
      char *value;
      if(line[len-1] == '\n')
         len--;
      value = malloc(len - i);
      for(j=0;j<i;j++)
         key[j] = line[j];
      key[i] = '\0';

      for(j=0;j<len - i;j++)
         value[j] = line[j+i+1];
      value[len-i-1] = '\0';
      loggerLog(LOG_DEBUG, "Line %s\tparsed as left=%s and right=%s.\n", line, key, value);
      dictPut(c->conf, key, value);
      free(line);
   } while(len != -1);
}
void configSaveConfig(config_t *c)
{
   //will be implemented later. Edit the thing by hand until we have a gui to edit it.
}
char *configGetString(config_t *c, char *key)
{
   return dictGet(c->conf, key);
}
int configGetInt(config_t *c,char *key)
{
   return atoi(dictGet(c->conf, key));
}
void configSetValue(config_t *c, char *key, char *value)
{
   char *oldVal = dictPut(c->conf, key, value);
   if(oldVal != NULL)
      free(oldVal);
}
void configExit(config_t *c)
{
   dictClearKeysVals(c->conf);

   free(c->conf);
   free(c);
}
